package com.devg.file.client.core;

import com.devg.file.client.core.async.AsyncUtil;
import com.devg.file.client.core.entity.FileClientConfig;
import com.devg.file.client.core.entity.FileResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;

public class WebUploadFile extends WebServiceRequest<File> {

  @Override
  public FileResponse invoke(File file, FileClientConfig fileClientConfig, String requestType) {
    FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("file", fileBody);
    fillMultipartEntityBuilder(builder, fileClientConfig);
    return invokeFile(builder, fileClientConfig, requestType);
  }

  @Override
  public FileResponse invoke(File file, String requestType) {
    return invoke(file, WebServiceRequest.fileClientConfig, requestType);
  }

  @Override
  public List<FileResponse> invoke(List<File> fileList, FileClientConfig fileClientConfig, String requestType) {
    List<FileResponse> list = new ArrayList<>();
    if (null != fileList && fileList.size() > 0) {
      AsyncUtil asyncUitl = AsyncUtil.newInstance();
      try {
        Class[] paramClass = new Class[]{File.class, FileClientConfig.class, String.class};
        for (int i = 0; i < fileList.size(); i++) {
          File file = fileList.get(i);
          Object[] paramObject = new Object[]{file, fileClientConfig, requestType};
          asyncUitl.addExecutePool("file" + i, this, "invoke", paramObject, paramClass);
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      } finally {
        asyncUitl.shutdown();
      }
      for (int i = 0; i < fileList.size(); i++) {
        FileResponse fileResponse = asyncUitl.getResult("file" + i);
        list.add(fileResponse);
      }
    }
    return list;
  }

  @Override
  public List<FileResponse> invoke(List<File> fileList, String requestType) {
    List<FileResponse> list = new ArrayList<>();
    if (null != fileList && fileList.size() > 0) {
      AsyncUtil asyncUitl = AsyncUtil.newInstance();
      try {
        Class[] paramClass = new Class[]{File.class, String.class};
        for (int i = 0; i < fileList.size(); i++) {
          File file = fileList.get(i);
          Object[] paramObject = new Object[]{file, requestType};
          asyncUitl.addExecutePool("file" + i, this, "invoke", paramObject, paramClass);
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      } finally {
        asyncUitl.shutdown();
      }
      for (int i = 0; i < fileList.size(); i++) {
        FileResponse fileResponse = asyncUitl.getResult("file" + i);
        list.add(fileResponse);
      }
    }
    return list;
  }
}
